package sh.grapendaal.tsuushin.module.uno.engine.impl;

import org.threeten.bp.Duration;
import org.threeten.bp.LocalDateTime;

import sh.grapendaal.tsuushin.module.uno.engine.StatisticsTracker;
import sh.grapendaal.tsuushin.module.uno.engine.domain.achievement.Achievement;
import sh.grapendaal.tsuushin.module.uno.engine.dto.GameReport;
import sh.grapendaal.tsuushin.module.uno.engine.event.GameEvent;

/*
 * Ideas for statistics:
 * - Pause gametimer after 1 minute of idling
 * - Keep track of average time per turn for player (no pausing here)
 * - Average score per player
 */
public class StatisticsTrackerImpl implements StatisticsTracker {
	
	private GameReport gameReport;
	
	private LocalDateTime lastActionTime;
	private Duration currentTurnDuration;
	
	public GameReport getGameReport() {
		return this.gameReport;
	}

	@Override
	public void onPlayerJoin(GameEvent event) {
		// Do nothing
	}

	@Override
	public void onPlayerLeave(GameEvent event) {
		// Do nothing
	}

	@Override
	public void onGameStart(GameEvent event) {
		this.gameReport = new GameReport();
		this.gameReport.setStartDate(LocalDateTime.now());
	}

	@Override
	public void onGameStop(GameEvent event) {
		this.gameReport.setEndDate(LocalDateTime.now());
	}

	@Override
	public void onGameEnd(GameEvent event) {
		this.gameReport.addGameState(event.getGameState());
		this.gameReport.setEndDate(LocalDateTime.now());
	}

	@Override
	public void onCardPlay(GameEvent event) {
		calculateTurnDuration();
		this.gameReport.addGameState(event.getGameState());
	}

	@Override
	public void onCardDraw(GameEvent event) {
		calculateTurnDuration();
		this.gameReport.addGameState(event.getGameState());
	}

	@Override
	public void onCardPass(GameEvent event) {
		calculateTurnDuration();
		this.gameReport.addGameState(event.getGameState());
	}

	@Override
	public void onTurnStart(GameEvent event) {
		resetTurnDuration();
		this.gameReport.addGameState(event.getGameState());
	}
	
	@Override
	public void onTurnSkip(GameEvent event) {
		this.gameReport.addGameState(event.getGameState());
	}

	@Override
	public void onTurnEnd(GameEvent event) {
		this.gameReport.addTotalPlayingTime(currentTurnDuration);
		//this.gameReport.addGameState(event.getGameState());
	}

	@Override
	public void onAchievementUnlock(GameEvent event, Achievement achievement) {
		// TODO Auto-generated method stub
		
	}
	
	private void resetTurnDuration() {
		this.lastActionTime = LocalDateTime.now();
		this.currentTurnDuration = Duration.ZERO;
	}

	private void calculateTurnDuration() {
		Duration duration = Duration.between(this.lastActionTime, LocalDateTime.now());
		this.currentTurnDuration = currentTurnDuration.plus(duration);
	}
}
